package thread;

import java.util.*;


/**
 * 并发安全的集合API
 * ArrayList,LinkedList,HashSet,都不是并发安全的
 */
public class SyncDemo5 {
    public static void main(String[] args) {
        // 模拟多线程向集合里面添加
//        List c = new ArrayList<>();
//        LinkedList c = new LinkedList<>();
//        Set c = new HashSet();

        // 将集合封装成线程安全的集合
//        List c = Collections.synchronizedList(new ArrayList<>());
        Set c = Collections.synchronizedSet(new HashSet<>());

        Thread t1 = new Thread(()->{
            for (int i = 0; i < 1000; i++){
                c.add(i);
            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 1000; i < 2000; i++){
                c.add(i);
            }
        });

        t1.start();
        t2.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("集合的大小为:" + c.size());
    }
}
